<template>
	<view class="app-game-manage-page">
		<view class="custom-search">
			<uni-search-bar class="search-input" placeholder="搜索应用名称" bgColor="#EEEEEE" clearButton="always" cancelButton="none" @confirm="onSearch"  v-model="keyword" @cancel="onCancel" @clear="clear"></uni-search-bar>
			<view class="search-txt" @click="submit">搜索</view>
		</view>
		<view class="list" v-if="appList.length">
			<list ref="listRef">
				<view v-for="(app, index) in appList" :key="Math.random() * 1000" class="list-item">
					<view class="slot-box"  @click="() => openShow(app)" >
						<image class="slot-image" :src="app.image" style="width: 50px; height: 50px;" mode="widthFix"></image>
						
						<view class="right-icon"  @click="() => openShow(app)" >
							<view class="title">{{ app.name }}</view>
						</view>
						
					</view>
					<view class="right-icon postion-about"  @click="() => openShow(app)" >
						<view class="nomal"
							:style="{color:  queryDailyStatus(app.dailyStatus,  app.dailyStartTime,app.dailyEndTime).color }"
							>
							{{ queryDailyStatus(app.dailyStatus,  app.dailyStartTime,app.dailyEndTime).txt }}</view>
							<image src="/static/icon/arrow-right.png" style="width: 30px; height: 30px;" mode="widthFix"></image>
					</view>
				</view>
			</list>
		</view>
		<view v-else>
			  <Empt description="暂无应用" /> 
		</view>
		
		<!-- 普通弹窗 -->
	 <Popup v-if="visible" :visible="visible"   @close="onClose">
			<view class="customVanPopupComponet">
				<view class="popup-main">
					<view class="header">
						<view class="cancal" @click="onClose">取消</view>
						<view class="save" @click="onSave">保存</view>
					</view>
					<view class="custom-popup-content">
						<radio-group :value="radio"  @change="onChangeRadio" class="radio-group">
							<radio  icon-size="24upx" color="#2BC888"  v-for="(r, i) in radios" :value="r.value" :checked="Number(r.value) === Number(radio)" :key="i">{{r.label}}</radio>
						</radio-group>
					</view>
					<view class="time-control" v-if="Number(radio) === 3">
						<view class="time">
							<view>
								<view class="time-item">
									<view class="title"> <image src="/static/icon/clock.png" style="width: 15px; height: 15px;" mode="widthFix"></image> 开始时间</view>
									<view class="right-select-time">
										<picker mode="time" :value="time" @change="bindTimeChange">
											<view class="uni-input custom-width">{{time}}</view>
										</picker>
										<image src="/static/icon/arrow.png" style="width: 21px; height: 24px;"  />
									</view>
								</view>
								<view class="time-item">
									<view class="title"> <image src="/static/icon/clock.png" style="width: 15px; height: 15px;" mode="widthFix"></image> 结束时间</view>
									<view class="right-select-time">
										<picker mode="time" :value="endTime" @change="bindEndTimeChange">
											<view class="uni-input custom-width">{{endTime}}</view>
										</picker>
										<image src="/static/icon/arrow.png" style="width: 21px;height: 24px;"/>
									</view>
								</view>
							</view>
							<view class="time-lang">限时：<view v-if="showTime">{{res}}</view></view>
						</view>
					</view>
				</view>
			</view>
		</Popup>

	

	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted } from 'vue'
	import { homeServer } from '@/common/index'
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import { urlHelp, mock } from '@/utils/index'
	import Empt from "@/components/Empt/index.vue"
	import Popup from "@/components/popup/index.vue"
	import { useBound } from "@/hooks/useBound.ts"
	const studentStore = useStudentListStore();
	const {tipBoundStudent, studentIsEmpt} = useBound();
	const curStd = computed(() => studentStore.currentStudent);
	const appList = ref([]);
	const showTime = ref(true)
	const popup = ref(null);
	const listRef = ref(null)
	const visible = ref(false);
	
	const queryDailyStatus = (dailyStatus, dailyStartTime, dailyEndTime) => {
		// 日常使用状态【1-禁用，2-不限时，3-限制时间段】
		const s = [
			{
				value: 1,
				label: '禁用',
				color: "#FF0000"
			},
			{
				value: 2,
				label: '不限制',
				color: "#000"
			},
			{
				value: 3,
				label: '限制时间段',
				color: "#4584FE"
			}
		];
		const { label = "", value, color } = s.find(c => c.value === Number(dailyStatus))
		let txt = ''
		if (value === 3) {
			txt = `限制时间段${dailyStartTime} - ${dailyEndTime}`
		} else {
			txt = label
		}

		return {
			txt,
			color
		}
	}
	// mock 数据
	const setMock = () => {
		const data = JSON.parse(JSON.stringify(mock.Single_APP_control))
		appList.value = data?.map(item => urlHelp.imgAddPrefix(item, 'image'));
	}
	// 获取应用列表
	const queryAppList = async () => {
		const studentId = curStd.value?.id;
		if (studentId) {
			try {
				const { status, data } = await homeServer.general({ studentId })
				if (status === '200') {
					appList.value = data?.map(item => urlHelp.imgAddPrefix(item, 'image'));
				}
			} catch (e) {
				console.log(e)
				//TODO handle the exception
			}
		} else {
			console.log('无法获取学生id')
		}
	}

	const radios = [
		{
			value: "1",
			label: '禁用'
		},
		{
			value: "2",
			label: '不限制'
		},
		{
			value: "3",
			label: '限时使用'
		}
	]


	// 禁用
	const disabledApp = async () => {
		const { id } = currentSelecteAppItem.value;
		if (!id) {
			console.log('appid 不存在')
			return;
		}
		try {
			const { status, data } = await homeServer.disabledApp({ id });
			if (status === '200') {
				uni.showToast({
					title: '设置禁用成功',
					icon: "success",
					success() {
						queryAppList()
					}
				})
			}
		} catch (e) {
			console.log(e)
			//TODO handle the exception
		}
	}
	// 不限制
	const updateAppNoDisabled = async () =>{
		const { id } = currentSelecteAppItem.value;
		if(id){
			try{
				const { status, data} = await homeServer.updateAppNoDisabled({id})
				if(status === '200'){
					uni.showToast({
						title: '设置不限制成功',
						icon: "success",
						success() {
							queryAppList()
						}
					})
				}
			}catch(e){
				console.log(e)
				//TODO handle the exception
			}
		}
	}

	// 不限制
	const limitUseTime = async (dailyStartTime, dailyEndTime) =>{
		const { id } = currentSelecteAppItem.value;
		if(id){
			try{
				const { status, data} = await homeServer.limitUseTime({id, dailyStartTime, dailyEndTime})
				if(status === '200'){
					uni.showToast({
						title: '设置限时使用成功',
						icon: "success",
						success() {
							queryAppList()
						}
					})
				}
			}catch(e){
				console.log(e)
				//TODO handle the exception
			}
		}
	}
	
	
	onMounted(async () => {
		if(!mock.isLogged()){
			setMock()
		}else {
			await queryAppList()
		}
	})



	const keyword = ref('');
	const onSearch = async ({value}) => {
		const detail = value
		if(studentIsEmpt.value){
			appList.value = mock.Single_APP_control.filter(app => app.name.includes(detail))
			keyword.value = detail;
			return
		}
				
		if(detail === ""){
			queryAppList();
			keyword.value = detail;
			return;
		}
		await queryAppList();
		appList.value = appList.value.filter(app => app.name.includes(detail))
		keyword.value = detail;
	}
	const submit = () => {
		onSearch({value: keyword.value})
	}
	const onCancel = (r) => { 
		console.log('取消')
		keyword.value = ""
		queryAppList();
	}
	
	const clear = () => {
		if(studentIsEmpt.value){
			setMock()
		}
		keyword.value = ""
		queryAppList();
	}

	const currentSelecteAppItem = ref({})
	const show = ref(false);
	const openShow = (app) => {
		if(studentIsEmpt.value){
			tipBoundStudent();
			return
		}
		show.value = true
		visible.value = true
		
		radio.value = app.dailyStatus.toString();
		const isEmpt = v => v ==="00:00" || v === "" || v === null || v === null;
		const isTimeEmpt = isEmpt(app.dailyStartTime) && isEmpt(app.dailyEndTime);
		if(isTimeEmpt){
			time.value = "请选择开始时间"
			endTime.value = "请选择结束时间"
		} else {
			time.value = app.dailyStartTime
			endTime.value = app.dailyEndTime
			queryRes(app.dailyStartTime, app.dailyEndTime)
		}
		currentSelecteAppItem.value = app;
	}
	const onClose = () => {
		visible.value = false
	}
	const onSave = () => {
		// radio
		console.log("radios", radios, radio.value)
	    const {value} =  radios.find(r => r.value === radio.value);
		console.log('value',value)
		if(value === '1'){ // 禁用
			disabledApp()
		}
		if(value === "2"){ // 不限制
		 updateAppNoDisabled()
		}
		if(value === '3'){ // 限时使用
			const dailyStartTime =  time.value;
			const dailyEndTime =endTime.value;
			const haveTime = (t: string) => t.includes(":")
			if(haveTime(dailyStartTime) && haveTime(dailyEndTime)){
				limitUseTime(dailyStartTime, dailyEndTime)
			}
		}
		onClose();
	}
	const radio = ref(null);
	const onChangeRadio = ({ detail }) => {
		console.log("detail", detail.value)
		radio.value = detail.value;
	};



	const res = ref("-");
	const queryRes = (s, e) => {
		const [s_s, s_e] = s.split(":").map(t => Number(t));
		const [e_s, e_e] = e.split(":").map(t => Number(t));
		let r = "";
		if (e_e > s_e || e_e == s_e) {
			r = (e_s - s_s) + '小时' + (e_e - s_e) + '分钟'
		} else {
			r = e_s - 1 - s_s + '小时' + (e_e + 60 - s_e) + '分钟'
		}
		showTime.value = false
		res.value = r;
		showTime.value = true
	}
	const validateTime = (s, e) => {
		const [s_s, s_e] = s.split(":").map(t => Number(t));
		const [e_s, e_e] = e.split(":").map(t => Number(t));
		return e_s > s_s || (e_s === s_s && e_e > s_e);
	}
	const toast = (msg = "结束时间不能小于开始时间") => {
		uni.showToast({
			title: msg,
			duration:1500,
			icon: "none"
		})
	}
	const time = ref('请选择时间');
	const endTime = ref("请选择时间");
	const bindEndTimeChange = (e) => {
		if(!time.value.includes(":")){ // 开始时间还没选
			endTime.value = e.detail.value
			return;
		}
		if (validateTime(time.value, e.detail.value)) {
			endTime.value = e.detail.value
			queryRes(time.value, endTime.value)
		} else {
			toast()
		}
	}
	const bindTimeChange = (e) => {
		if(!endTime.value.includes(":")){ // 结束时间还没选
			time.value = e.detail.value
			return;
		}
		if (validateTime(e.detail.value, endTime.value)) {
			time.value = e.detail.value
			queryRes(time.value, endTime.value)
		} else {
			toast("开始时间不得超过结束时间")
		}
	}
</script>


<style lang="scss">
	page {
		background-color: #f5f9fa;
	}

	.app-game-manage-page {
		.list {
			padding: 20upx 0 30upx 0;
			.title {
				// margin-left: $appIconLeftMarg;
				color: #000;
				height: 100%;
				display: flex;
				align-items: center;
				font-size: $appIconTxt;
			}

			.right-icon {
				display: flex;
				justify-content: flex-end;
				align-items: center;

				.nomal {
					font-size: $appIconTxt;
				}

				.red {
					color: #a32b34;
				}

				.greed {
					color: #2bc888;
				}
			}
		}
	}
</style>

<style scoped lang="scss">
	.app-game-manage-page {
		.list {
			background-color: #fff;
			margin-top: 40upx;
		}
	}
</style>

<style lang="scss" scoped>
	.popup-main {
		.header {
			display: flex;
			justify-content: space-between;
			padding: 20upx;

			.cancal {

				text-align: left;
			}

			.save {
				text-align: right;
			}
		}

		.custom-popup-content {
			margin-top: 40upx;

			.radio-group {
				display: flex;
				justify-content: space-evenly;
				align-items: center;
				.van-radio-group {
					display: flex;
					justify-content: space-around;
				}
			}
		}
	}


	.time-control {
		margin-top: 80upx;

		.time {
			.time-item{
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20upx;
			}
			.title {
				margin-left: 10upx;
			}

			.right-select-time {
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.time-lang {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 40upx;
			margin-bottom: 40upx;
			width: 100%;
			color: #2d2d2d;
			text-align: center;
			font-size: 32upx;
		}
	}
	
	.customVanPopupComponet{
		.popup-main{
			min-height: 250upx;
		}
	}
	
	.custom-width{
		width: 500upx;
		text-align: right;
	}
	
	// .list-item{
	// 	display: flex;
	// 	align-items: center;
	// 	justify-content: space-between;
	// 	padding: 0 30upx;
	// 	margin: 30upx 0;
	// 	.left-icon-title{
	// 		display: flex;
	// 		align-items: center;
	// 		justify-content: flex-start;
	// 	}
	// }
	
	.list-item{
		position: relative;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 40upx;
		.postion-about{
			position: absolute;
			right: 30upx;
			top: 37%;
		}
	}
	
	.slot-box {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			align-items: center;
			margin-left: 30upx;
		}
	
		.slot-image {
			/* #ifndef APP-NVUE */
			display: block;
			/* #endif */
			margin-right: 10px;
			width: 30px;
			height: 30px;
		}
	
		.slot-text {
			flex: 1;
			font-size: 14px;
			color: #4cd964;
			margin-right: 10px;
		}
		
		.custom-search{
			display: flex;
			align-items: center;
			width: 100%;
			.search-input{
				width: 100%;
			}
			.search-txt{
				width: 100upx;
				font-size: 28upx;
				color: #2d2d2d;
			}
		}
		
</style>